package com.gaojiabao.panghu.interceptor;

import com.alibaba.fastjson.JSON;
import com.gaojiabao.panghu.constant.ResultCodeEnum;
import com.gaojiabao.panghu.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: gaojiabao
 * @Date: 2024/11/4 9:18
 * @Describe 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String loginUUID = request.getHeader("Token");
        //token => null "" " "
        if (StringUtils.isBlank(loginUUID)) {
            returnNotLogin(response);
            return false;
        }
        //redis中的对象 => null
        Object userId = redisTemplate.opsForHash().get(loginUUID, "id");
        if (null == userId) {
            returnNotLogin(response);
            return false;
        }
        //token续期
        redisTemplate.expire(loginUUID, 3, TimeUnit.HOURS);
        //已登录放行
        return true;
    }

    /*========================================*/

    //提取函数——返回未登录信息
    private void returnNotLogin(HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        //返回状态码 和 响应编码
        response.setStatus(200);
        response.setContentType("Application/json;charset=utf-8");
        //构造返回响应体
        String resultStr = JSON.toJSONString(Result.build(null, ResultCodeEnum.NOTLOGIN));
        outputStream.write(resultStr.getBytes());
    }
}
